package org.example.springboot_dynamicdatasource.dynamic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
@Primary
public class DynamicDatasource extends AbstractRoutingDataSource {
    public static ThreadLocal<String> dsType = new ThreadLocal<>();

    @Autowired
    DataSource dataSource1;

    @Autowired
    DataSource dataSource2;

    @Override
    protected Object determineCurrentLookupKey() {
        return dsType.get();
    }

    @Override
    public void afterPropertiesSet() {
        Map<Object, Object> m = new HashMap<>();
        m.put("w", dataSource1);
        m.put("r", dataSource2);
        super.setTargetDataSources(m);
        super.setDefaultTargetDataSource(dataSource1);

        dsType.set("w");
        super.afterPropertiesSet();
    }
}
